package com.walle.core.utils;

import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * 阿里OSS工具类
 * @author Wall-E.Caesar Liu
 * @date 2021/11/23 22:14
 */
@Service
public class AliOSS {

    @Value("${oss.aliyun.access-key-id}")
    private String accessKeyId;

    @Value("${oss.aliyun.access-key-secret}")
    private String accessKeySecret;

    @Value("${oss.aliyun.bucket-name}")
    private String bucket;

    @Value("${oss.aliyun.endpoint}")
    private String endpoint;

    /**
     * 上传文件
     *
     * @param file 文件
     * @param fileKey 文件的key
     */
    public void upload(MultipartFile file, String fileKey) throws IOException {
        com.aliyun.oss.OSS ossClient = this.getOSSClient();
        ossClient.putObject(bucket, fileKey, file.getInputStream());
        ossClient.shutdown();
    }

    /**
     * 下载文件
     *
     * @author Caesar Liu
     * @date 2019-09-25 14:25
     */
    public InputStream download(String fileKey) {
        com.aliyun.oss.OSS ossClient = this.getOSSClient();
        OSSObject file = ossClient.getObject(bucket, fileKey);
        return file.getObjectContent();
    }

    /**
     * 获取OSS客户端对象
     */
    private com.aliyun.oss.OSS getOSSClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

}
